package com.pls.action;

import java.util.ArrayList;

import org.apache.log4j.Logger;

import com.pls.constants.ValidationErrorEnum;
import com.pls.domain.BaseRequest;
import com.pls.domain.BaseResponse;
import com.pls.domain.ValidationError;

public abstract class BaseRequestHandler<TResponse extends BaseResponse, TRequest extends BaseRequest> {

	private Class<TResponse> tResponse;
	Logger logger = Logger.getLogger(BaseRequestHandler.class);
	
	public BaseRequestHandler(Class<TResponse> tResponse) {
		this.tResponse = tResponse;
	}

	private TResponse buildResponse() throws InstantiationException,
			IllegalAccessException {
		return tResponse.newInstance();
	}

	/*
	 * Execute validation and process
	 */
	public TResponse Execute(TRequest request) {
		logger.debug("- execute method entered");
		ArrayList<ValidationError> validationErrors = new ArrayList<ValidationError>();

		validationErrors = validate(request);
		if (validationErrors.size() > 0) {
			TResponse response = null;

			try {
				response = buildResponse();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				logger.debug( "- Response build error.");
				ValidationError error = new ValidationError();
				error.setMessage("Error building response.");
				error.setErrorName(ValidationErrorEnum.ReponseFatalError);
				validationErrors.add(error);
			}
			response.setValidationErrors(validationErrors);
			
			logger.debug("- execute method exited.");
			return response;
		}

		// Get validation errors
		TResponse response = process(request);
		// response.setValidationErrors(validationErrors);

		return response;
	}

	/*
	 * Generic validation method. Checks if request is null
	 */
	protected ArrayList<ValidationError> validate(TRequest request) {
		ArrayList<ValidationError> errors = new ArrayList<ValidationError>();

		if (request == null) {
			ValidationError valError = new ValidationError();
			valError.setMessage("Request is null.");
			valError.setErrorName(ValidationErrorEnum.NullRequest);
			errors.add(valError);
		}

		return errors;
	}

	protected TResponse process(TRequest request) {
		TResponse response = null;
		return response;
	}
}
